<template>
  <div>
    <el-collapse v-model="activeNames" style="padding: 0 20px 20px; border: none">
      <el-collapse-item
        v-for="(item, listIndex) in value"
        :key="listIndex"
        :title="recordKey === 'equipItems' ? item.equipName : recordKey === 'gasSectionItems' ? item.productSection : recordKey === 'gasPollutionItems' ? ('排气筒'+item.exhaustFunnelNo + ', 污染因子' + item.pollutionFactor) : (title + '-' + (listIndex+1))"
        :name="recordKey + listIndex"
      >
        <template v-for="attr in attrs">
          <el-form-item v-if="justifyFieldDep(listIndex, attr.depKey, attr.depValue)" :key="attr.key" :label="attr.title">
            <el-select
              v-if="attr.type === 'select'"
              v-model="value[listIndex][attr.key]"
              :disabled="disabled"
              placeholder="请选择"
              class="input"
              @change="handleChange"
            >
              <el-option
                v-for="dict in dict.type[attr.dictType]"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>

            <el-date-picker
              v-else-if="['date', 'datetime'].includes(attr.type)"
              v-model="value[listIndex][attr.key]"
              :disabled="disabled"
              :type="attr.type"
              placeholder="选择时间"
              class="input"
              @change="handleChange"
            />

            <el-upload
              v-else-if="attr.type === 'file'"
              action="#"
              list-type="picture-card"
              multiple
              class="input"
              :disabled="disabled"
              :file-list="value[listIndex][attr.key]"
              :auto-upload="false"
              :on-preview="previewFile"
              :before-remove="beforeRemoveFile"
              :on-remove="(file, fileList) => deleteFile(file, fileList, listIndex)"
              :on-change="(file, fileList) => addFile(file, fileList, listIndex)"
            >
              <i class="el-icon-plus" />
            </el-upload>

            <el-input
              v-else-if="attr.key === 'equipNumDiff'"
              :value="value[listIndex].equipCurNum - value[listIndex].equipHisNum"
              type="text"
              disabled
              class="input"
            />

            <el-input
              v-else
              v-model="value[listIndex][attr.key]"
              :disabled="disabled"
              :type="attr.type ? attr.type : 'text'"
              class="input"
              :placeholder="attr.placeholder || '请输入内容'"
              @change="handleChange"
            />
          </el-form-item>
        </template>
      </el-collapse-item>
    </el-collapse>

    <el-dialog :visible.sync="dialogVisible" append-to-body>
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
  </div>
</template>
<script>
import { saveAs } from 'file-saver'
import { isImage } from '@/utils'
import { deleteFile } from '@/api/system/file'

export default {
  name: 'MultipleForm',
  props: {
    disabled: Boolean,
    recordKey: String,
    value: {
      type: Array,
      default: () => []
    },
    dict: {
      type: Object,
      default: () => ({})
    },
    attrs: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      activeNames: [],
      dialogImageUrl: '',
      dialogVisible: false
    }
  },
  watch: {
    recordKey: {
      immediate: true,
      handler: function(val) {
        this.activeNames = this.activeNames.length > 0 ? this.activeNames : [`${val}0`]
      }
    }
  },
  methods: {
    justifyFieldDep(index, keys, defaultValues) {
      if (typeof (keys) === 'string') {
        if (!keys) return true
        return this.value[index][keys] === defaultValues
      } else {
        if (!keys || !defaultValues || (keys.length !== defaultValues.length)) {
          return true
        }
        var i = 0; var len = keys.length
        for (; i < len; i++) {
          if (this.value[index][keys[i]] !== defaultValues[i]) {
            return false
          }
        }
        return true
      }
    },

    handleChange() {
      this.$emit('input', this.value)
      this.$emit('change', this.value)
    },
    beforeRemoveFile(file) {
      return new Promise((resolve, reject) => {
        this.$modal.confirm(`确认删除？`).then(function() {
          resolve()
        }).catch(() => {
          reject()
        })
      })
    },
    async deleteFile(file, fileList, listIndex) {
      if (file.id) {
        await deleteFile(file.id)
      }
      this.value[listIndex].files = fileList
      this.handleChange()
    },
    addFile(file, fileList, listIndex) {
      this.value[listIndex].files.push(file)
      this.handleChange()
    },
    getFileBlobUrl(file) {
      if (window.createObjectURL) {
        return window.createObjectURL(file)
      } else if (window.URL) {
        return window.URL.createObjectURL(file)
      } else if (window.webkitURL) {
        return window.webkitURL.createObjectURL(file)
      }
    },
    previewFile(file) {
      if (file.raw) {
        if (file.raw.type.includes('image')) {
          const url = this.getFileBlobUrl(file.raw)
          this.dialogImageUrl = url
          this.dialogVisible = true
        } else {
          saveAs(file.raw)
        }
      } else if (isImage(file.url.split('.').pop())) {
        this.dialogImageUrl = file.url
        this.dialogVisible = true
      } else {
        saveAs(file.url)
      }
    }
  }
}
</script>

